# -*- coding: utf-8 -*-

__Author__ = "NianJiu"
__QQ__ = 1670829014
__Email__ = "soliton.wang@gmail.com"

import json
import time

import requests


class Mfpad:
    def __init__(self, TOKEN: str, UUID: str):
        self.session = requests.Session()

        self.headers = {
            'Accept': 'application/json',
            'Authorization': f'Bearer {TOKEN}',
            'Accept-Language': 'zh',
        }

        self.url = f"https://api.mfpad.com/v4/org/{UUID}"

    def add_redirect(self, new_domain: str, redirect_domain: str):
        # 添加URL转发解析
        """
        :param new_domain:  源URL地址
        :param redirect_domain: 重定向URL地址
        :return: 返回成功或失败信息
        """
        url = self.url + "/redirect"

        data = self.get_body(new_domain, redirect_domain)

        result = self.session.post(url=url, headers=self.headers, data=data).json()
        try:
            if result['message'] == "重定向记录 超出了套餐限制，请升级套餐后再尝试":
                return result['message']
            elif result['message'] == f"记录已存在 {new_domain} ":
                return result['message']
        except KeyError:
            return "添加重定向成功"

    def del_group_redirect(self, source_url_list: list):
        # 删除指定的重定向解析
        """
        :param source_url_list: 源URL地址
        :return: 返回删除结果
        """

        source_ids = [self.get_source_id(x) for x in source_url_list]

        url = self.url + "/redirect"

        data = json.dumps({
            "ids": source_ids
        })

        self.headers['Content-Type'] = 'application/json'
        result = requests.delete(url=url, headers=self.headers, params=data, data=data)

        if result.status_code == 204:
            return "源URL地址删除成功"
        else:
            return f"源URL地址不存在或有误, 状态码: {result.status_code}"

    def del_redirect(self, source_url: str):
        # 删除多个(组)重定向记录
        """
        :param source_url: list 存放多个源URL地址
        :return: 输出删除成功或失败
        """

        source_ids = str(self.get_source_id(source_url))

        url = self.url + "/redirect/" + source_ids

        result = requests.delete(url=url, headers=self.headers)

        if result.status_code == 204:
            return f"{source_url} -> 删除成功"
        else:
            return f"{source_url} -> 没有此源URL"

    @staticmethod
    def get_body(new_domain: str, redirect_domain: str):
        """
        :param new_domain:  源URL地址
        :param redirect_domain: 重定向URL地址
        :return: 返回body内容体
        """
        data = {
            "url": new_domain,
            "type": "common",
            "file": "*",
            "filters": [],
            "value": redirect_domain,
            "handler": "redirect",
            "title": "",
            "description": "",
            "monitor": "",
            "forward_query": "true",
            "forward_path": "true",
            "urls_dispatch": "order",
            "urls_list": []
        }
        return data

    def get_source_id(self, source_url: str):
        # 获取指定的源URL地址信息ID
        """
        :param source_url: 源URL地址
        :return: 返回 string id
        """
        get_source_ids = self.get_redirect_list()

        for source_ids in get_source_ids:

            if source_ids['host'] == source_url:
                ids = source_ids['id']
                return ids

    def get_redirect_list(self):
        """
        :return: 返回现有的重定向配置信息 list
        """
        url = self.url + "/redirect?page=1"

        data = requests.get(
            url=url, headers=self.headers, params={}
        ).json()

        return data

    def get_dns_info(self, source_url_list: list):
        # 查询dns信息, list 传入源URL地址
        """
        :param source_url_list:
        :return:
        """
        if len(source_url_list) == 1:
            hosts = source_url_list
        else:
            hosts = ','.join(source_url_list)
        url = self.url + "/host/get_dns_setup"
        params = {
            "hosts": hosts
        }

        result = requests.get(url=url, headers=self.headers, params=params).json()
        return result

    def get_redirect_record(self, source_url):
        """
        :param source_url: 通过源URL域名获取指定重定向记录
        :return: 输出指定的重定向记录
        """
        source_ids = self.get_source_id(source_url)

        url = self.url + "/redirect/" + str(source_ids)
        result = requests.get(url=url, headers=self.headers).json()
        return result

    def get_dns_value(self, source_url: list):
        data = self.get_dns_info(source_url_list=source_url)
        return data['data'][0]['required_value']

    def update_redirect(self, old_source_url, new_source_url, new_source_value):
        # 根据旧的源URL地址获取ID修改解析
        """
        :param old_source_url: 旧 源URL地址
        :param new_source_url: 新 源URL地址
        :param new_source_value: 新 重定向地址
        :return: 输出更新成功或失败
        """

        source_id = str(self.get_source_id(old_source_url))

        url = self.url + "/redirect/" + source_id

        params = {
            "id": source_id
        }

        data = self.get_body(new_domain=new_source_url, redirect_domain=new_source_value)

        result = requests.put(url=url, headers=self.headers, params=params, data=data)
        if result.status_code == 200:
            return "源URL地址更新成功"
        else:
            return "源URL地址不存在"
